//
//  DashboardDeptController.m
//  APJ HRadar
//
//  Created by Luna Gao on 14-4-15.
//  Copyright (c) 2014年 APJ. All rights reserved.
//A

#import "DashboardDeptController.h"
#import "HRStore.h"
#import "Dept.h"
#import "ResourceRequirement.h"
#import "RequirementDetail.h"

@implementation DashboardDeptController

@synthesize view;
@synthesize _navigationController;

-(void)sentNavigationController:(UINavigationController *)navigationController
{
    self._navigationController = navigationController;
}

- (void)viewDidLoad
{
    
    [self getDeptView];
}


-(UIView *)getDeptView;
{
    CGRect frame;
    frame.size.width = 1000;
    frame.size.height = 580;
    frame.origin.x = 0;
    frame.origin.y = 0;
    self.view = [[UIView alloc] initWithFrame:frame];
    UISwipeGestureRecognizer *gestureLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(next:)];
    [gestureLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
    [self.view addGestureRecognizer:gestureLeft];
    
    UISwipeGestureRecognizer *gestureRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(prev:)];
    [gestureRight setDirection:UISwipeGestureRecognizerDirectionRight];
    [self.view addGestureRecognizer:gestureRight];
    
    [self loadLegend];
    [self SetupChart];
    [self bindDateForChart];
    return self.view;
}

-(void) loadLegend
{
    UILabel *legendLabel = [[UILabel alloc] init];
    legendLabel.text = @"Legend:";
    [legendLabel setFrame:CGRectMake(50, 605, 300, 50)];
    [self.view addSubview:legendLabel];
    
    UIProgressView *req = [[UIProgressView alloc] init];
    [req setFrame:CGRectMake(130, 630, 50, 50)];
    CGAffineTransform transform = CGAffineTransformMakeScale(1.0f, 8.0f);
    req.transform = transform;
    [req setTrackTintColor:[UIColor colorWithRed:0.400 green:0.400 blue:0.800 alpha:1.000]];
    [view addSubview:req];
    
    UILabel *reqLabel = [[UILabel alloc] init];
    reqLabel.text = @"The current month's requirements.";
    [reqLabel setFrame:CGRectMake(160, 605, 300, 50)];
    transform = CGAffineTransformMakeScale(0.8f, 0.8f);
    reqLabel.transform = transform;
    [view addSubview:reqLabel];
    
    
    //Requirement Meet
    UIProgressView *arch = [[UIProgressView alloc] init];
    [arch setFrame:CGRectMake(130, 650, 50, 50)];
    transform = CGAffineTransformMakeScale(1.0f, 8.0f);
    arch.transform = transform;
    [arch setTrackTintColor:[UIColor colorWithRed:0.400 green:0.800 blue:0.000 alpha:1.000]];
    [view addSubview:arch];
    
    UILabel *archLabel = [[UILabel alloc] init];
    archLabel.text = @"Has completed the requirements";
    [archLabel setFrame:CGRectMake(160, 627, 300, 50)];
    transform = CGAffineTransformMakeScale(0.8f, 0.8f);
    archLabel.transform = transform;
    [view addSubview:archLabel];
    
    
    //Outstanding
    UIProgressView *outstandingReq = [[UIProgressView alloc] init];
    [outstandingReq setFrame:CGRectMake(130, 672, 50, 50)];
    transform = CGAffineTransformMakeScale(1.0f, 8.0f);
    outstandingReq.transform = transform;
    [outstandingReq setTrackTintColor:[UIColor colorWithRed:1.000 green:0.600 blue:0.200 alpha:0.920]];
    [view addSubview:outstandingReq];
    
    UILabel *outstandingLabel = [[UILabel alloc] init];
    outstandingLabel.text = @"The historical requirements";
    [outstandingLabel setFrame:CGRectMake(160, 650, 300, 50)];
    transform = CGAffineTransformMakeScale(0.8f, 0.8f);
    outstandingLabel.transform = transform;
    [view addSubview:outstandingLabel];
    
    
}

- (void)SetupChart
{
	_barColors						= @[[UIColor blueColor], [UIColor redColor], [UIColor blackColor], [UIColor orangeColor], [UIColor purpleColor], [UIColor greenColor], [UIColor yellowColor]];
	_currentBarColor				= 0;
	CGRect chartFrame				= CGRectMake(10,170,1000.0,400.0);
	_chart							= [[SimpleBarChart alloc] initWithFrame:chartFrame];
	//_chart.center					= CGPointMake(self.view.frame.size.width / 2.0, self.view.frame.size.height / 5);
	_chart.delegate					= self;
	_chart.dataSource				= self;
	_chart.barShadowOffset			= CGSizeMake(2.0, 1.0);
	_chart.animationDuration		= 1.0;
	_chart.barShadowColor			= [UIColor grayColor];
	_chart.barShadowAlpha			= 0.5;
	_chart.barShadowRadius			= 1.0;
	_chart.barWidth					= 18.0;
	_chart.xLabelType				= SimpleBarChartXLabelTypeHorizontal;
	_chart.incrementValue			= 1;
	_chart.barTextType				= SimpleBarChartBarTextTypeTop;
	_chart.barTextColor				= [UIColor whiteColor];
	_chart.gridColor				= [UIColor grayColor];
    
	[self.view addSubview:_chart];
    
    monthLabel = [[UILabel alloc] init];
    monthLabel.frame = CGRectMake(40, 100, 200, 50);
    monthLabel.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
    [self.view addSubview:monthLabel];
}

- (void)bindDateForChart
{
    if (!_deptList) {
        _deptList = [[HRStore sharedStore] allDept];
    }
    

    //SA###########
    if(!_saMonthRequirements){
        _saMonthRequirements = [[NSMutableArray alloc] init];
    }else{
        [_saMonthRequirements removeAllObjects];
    }
    if(!_saMeetRequirements){
        _saMeetRequirements = [[NSMutableArray alloc] init];
    }else{
        [_saMeetRequirements removeAllObjects];
    }
    
    if(!_saLegacyRequirements){
        _saLegacyRequirements = [[NSMutableArray alloc] init];
    }else{
        [_saLegacyRequirements removeAllObjects];
    }
    
    //AP###########
    if(!_apMonthRequirements){
        _apMonthRequirements = [[NSMutableArray alloc] init];
    }else{
        [_apMonthRequirements removeAllObjects];
    }
    if(!_apMeetRequirements){
        _apMeetRequirements = [[NSMutableArray alloc] init];
    }else{
        [_apMeetRequirements removeAllObjects];
    }
    
    if(!_apLegacyRequirements){
        _apLegacyRequirements = [[NSMutableArray alloc] init];
    }else{
        [_apLegacyRequirements removeAllObjects];
    }
    //P###########
    if(!_pMonthRequirements){
        _pMonthRequirements = [[NSMutableArray alloc] init];
    }else{
        [_pMonthRequirements removeAllObjects];
    }
    if(!_pMeetRequirements){
        _pMeetRequirements = [[NSMutableArray alloc] init];
    }else{
        [_pMeetRequirements removeAllObjects];
    }
    
    if(!_pLegacyRequirements){
        _pLegacyRequirements = [[NSMutableArray alloc] init];
    }else{
        [_pLegacyRequirements removeAllObjects];
    }
    
    //###########
    if (!_currentMonth) {
        _currentMonth = [NSDate date];
    }
    
    if(!_lastMonth){
        NSDateComponents* cmpnts = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:_currentMonth];
        cmpnts.month -= 1;
        _lastMonth = [[NSCalendar currentCalendar] dateFromComponents:cmpnts];
    }
    
    for (Dept *dept in _deptList) {
        
        //        int sum = 0;
        //        int subSum = 0;
        //        int outstandingSum = 0;
        
        
        int totalSaLegacyReq =0;
        int totalApLegacyReq =0;
        int totalPLegacyReq =0;
        
        int totalSaReq =0;
        int totalApReq =0;
        int totalPReq =0;
        
        int totalSaMeetReq =0;
        int totalApMeetReq =0;
        int totalPMeetReq =0;
        
        
        
        //跟据Dept取出所有需求 时间范围是从开始到上一个月的数据
        NSDate *lastMonth;
        NSDateComponents* cmpnts = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:_currentMonth];
        cmpnts.month -= 1;
        lastMonth=[[NSCalendar currentCalendar] dateFromComponents:cmpnts];
        
        //格式化当前日期
        NSDate *nowMonth;
        NSDateComponents* nowCmpnts = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:[NSDate date]];
        nowMonth=[[NSCalendar currentCalendar] dateFromComponents:nowCmpnts];
        
        NSArray *saReqs =[[HRStore sharedStore] positionRequirementsByDept:dept.deptId  inMonth:[_currentMonth timeIntervalSince1970] position:@"SA" ];
        NSArray *apReqs =[[HRStore sharedStore] positionRequirementsByDept:dept.deptId  inMonth:[_currentMonth timeIntervalSince1970] position:@"AP" ];
        NSArray *pReqs =[[HRStore sharedStore] positionRequirementsByDept:dept.deptId  inMonth:[_currentMonth timeIntervalSince1970] position:@"P" ];

        
        //获取到这个月前的Dept 对应的Req数据（非取消的数据）
        NSArray *saLegacyReqs =[[HRStore sharedStore] getLegacyRequirementsByDept:dept.deptId  inMonth:[lastMonth timeIntervalSince1970] position:@"SA" ];
        NSArray *apLegacyReqs =[[HRStore sharedStore] getLegacyRequirementsByDept:dept.deptId  inMonth:[lastMonth timeIntervalSince1970] position:@"AP" ];
        NSArray *pLegacyReqs =[[HRStore sharedStore] getLegacyRequirementsByDept:dept.deptId  inMonth:[lastMonth timeIntervalSince1970] position:@"P" ];
        
        NSMutableArray *currentMonthTotalReqsForSa = [[NSMutableArray alloc] init];
        if([saReqs count]!=0){
            for (ResourceRequirement *object in saReqs) {
                [currentMonthTotalReqsForSa addObject:object];
            }
            }
        
        NSMutableArray *currentMonthTotalReqsForAp= [[NSMutableArray alloc] init];
        if([apReqs count]!=0){
            
            for (ResourceRequirement *object in apReqs) {
                [currentMonthTotalReqsForAp addObject:object];
            }
        
        }
        
        NSMutableArray *currentMonthTotalReqsForP= [[NSMutableArray alloc] init];
        if([pReqs count]!=0){
            
            for (ResourceRequirement *object in pReqs) {
                [currentMonthTotalReqsForP addObject:object];
            }
        }
        
        
        for (ResourceRequirement *req in saLegacyReqs) {

//            NSArray *confirmReq = [[HRStore sharedStore] confirmedInterviewForReqAndPosition:req.reqId position:@"SA" ] ;
            //查找选中月份已满足的需求
            NSArray *confirmReq = [[HRStore sharedStore] getLegacyconfirmedInterviewForReq:req.reqId inMonth:[lastMonth timeIntervalSince1970]  ] ;
            //选中月份之前没满足需求数
            totalSaLegacyReq +=  (req.count - [confirmReq count]);
            
            if((req.count - [confirmReq count])>0)
            {
                [currentMonthTotalReqsForSa addObject:req];
            }
            
        }
        
        for (ResourceRequirement *req in apLegacyReqs) {
            
            
            
//            NSArray *confirmReq = [[HRStore sharedStore] confirmedInterviewForReqAndPosition:req.reqId position:@"AP" ] ;
            //查找选中月份已满足的需求
            NSArray *confirmReq = [[HRStore sharedStore] getLegacyconfirmedInterviewForReq:req.reqId inMonth:[lastMonth timeIntervalSince1970]  ] ;
            //选中月份之前没满足需求数
            totalApLegacyReq +=  (req.count - [confirmReq count]);
            
            if((req.count - [confirmReq count])>0)
            {
                [currentMonthTotalReqsForAp addObject:req];
            }
        }
        
        for (ResourceRequirement *req in pLegacyReqs) {
            
            
            //查找已满足的需求
//            NSArray *confirmReq = [[HRStore sharedStore] confirmedInterviewForReqAndPosition:req.reqId position:@"P" ] ;
            //查找选中月份已满足的需求
            NSArray *confirmReq = [[HRStore sharedStore] getLegacyconfirmedInterviewForReq:req.reqId inMonth:[lastMonth timeIntervalSince1970]  ] ;
            //选中月份之前没满足需求数
            totalPLegacyReq +=  (req.count - [confirmReq count]);
            
            if((req.count - [confirmReq count])>0)
            {
                [currentMonthTotalReqsForP addObject:req];
            }
        }
        
        //##############
        
        for (ResourceRequirement *object in saReqs) {
            //需求数
            totalSaReq += object.count;
        }
        
        for (ResourceRequirement *req in currentMonthTotalReqsForSa) {
            
            
            //查找已满足的需求
//            NSArray *confirmReq = [[HRStore sharedStore] confirmedInterviewForReqAndPosition:req.reqId position:@"SA" ] ;
            //查找选中月份已满足的需求
            NSArray *confirmReq = [[HRStore sharedStore] getCurrentMonthconfirmedInterviewForReq:req.reqId inMonth:[_currentMonth timeIntervalSince1970]  ] ;
            totalSaMeetReq+= [confirmReq count];
            
            
        }
        
        for (ResourceRequirement *object in apReqs) {
            //需求数
            totalApReq += object.count;
        }
        
        for (ResourceRequirement *req in currentMonthTotalReqsForAp) {
            
                       //查找已满足的需求
//            NSArray *confirmReq = [[HRStore sharedStore] confirmedInterviewForReqAndPosition:req.reqId position:@"AP" ] ;
            
            //查找选中月份已满足的需求
            NSArray *confirmReq = [[HRStore sharedStore] getCurrentMonthconfirmedInterviewForReq:req.reqId inMonth:[_currentMonth timeIntervalSince1970]  ] ;
            totalApMeetReq+=[confirmReq count];
            
            
        }
        
        for (ResourceRequirement *object in pReqs) {
            //需求数
            totalPReq += object.count;
        }
        
        for (ResourceRequirement *req in currentMonthTotalReqsForP) {
                        //查找已满足的需求
//            NSArray *confirmReq = [[HRStore sharedStore] confirmedInterviewForReqAndPosition:req.reqId position:@"P" ] ;
            
           
            //查找选中月份已满足的需求
            NSArray *confirmReq = [[HRStore sharedStore] getCurrentMonthconfirmedInterviewForReq:req.reqId inMonth:[_currentMonth timeIntervalSince1970]  ] ;
            totalPMeetReq+=[confirmReq count];
            
        }

        
        NSDate *tempFormartCurrentMonth; ;
        NSDateComponents* tempCmpnts = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:_currentMonth];
        tempFormartCurrentMonth = [[NSCalendar currentCalendar] dateFromComponents:tempCmpnts];
        
        
        
        if([[tempFormartCurrentMonth laterDate:nowMonth] isEqualToDate:nowMonth] || [tempFormartCurrentMonth isEqualToDate:nowMonth])
        {
            totalSaLegacyReq+=totalSaReq;
            totalApLegacyReq+=totalApReq;
            totalPLegacyReq+=totalPReq;
        }
        else
        {
            
            totalSaLegacyReq=totalSaReq;
            totalApLegacyReq=totalApReq;
            totalPLegacyReq=totalPReq;

        }
        
        [_saMonthRequirements addObject:[NSNumber numberWithInt:totalSaReq]];
        [_saMeetRequirements addObject:[NSNumber numberWithInt:totalSaMeetReq]];
        [_saLegacyRequirements addObject:[NSNumber numberWithInt:totalSaLegacyReq]];
        
        [_apMonthRequirements addObject:[NSNumber numberWithInt:totalApReq]];
        [_apMeetRequirements addObject:[NSNumber numberWithInt:totalApMeetReq]];
        [_apLegacyRequirements addObject:[NSNumber numberWithInt:totalApLegacyReq]];
        
        [_pMonthRequirements addObject:[NSNumber numberWithInt:totalPReq]];
        [_pMeetRequirements addObject:[NSNumber numberWithInt:totalPMeetReq]];
        [_pLegacyRequirements addObject:[NSNumber numberWithInt:totalPLegacyReq]];

        
    }
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"MMM YYYY"];
    monthLabel.text = [format stringFromDate:_currentMonth];
    [_chart reloadData];
    
       
}

- (UIColor *)barChart:(SimpleBarChart *)barChart colorForBarAtIndex:(NSUInteger)index
{
	return [_barColors objectAtIndex:_currentBarColor];
}


- (void)prev:(UISwipeGestureRecognizer *)gesture
{
    NSDateComponents* cmpnts = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:_currentMonth];
    cmpnts.month -= 1;
    _currentMonth = [[NSCalendar currentCalendar] dateFromComponents:cmpnts];
    [self bindDateForChart];
}

- (void)next:(UISwipeGestureRecognizer *)gesture
{
    NSDateComponents* cmpnts = [[NSCalendar currentCalendar] components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:_currentMonth];
    cmpnts.month += 1;
    _currentMonth = [[NSCalendar currentCalendar] dateFromComponents:cmpnts];
    [self bindDateForChart];
}

- (NSUInteger)numberOfBarsInBarChart:(SimpleBarChart *)barChart
{
    	return (_deptList.count);
}



//##########
- (CGFloat)barChart:(SimpleBarChart *)barChart valueForSaMonthRequirementsBarAtIndex:(NSUInteger)index
{
	return [[_saMonthRequirements objectAtIndex:index] floatValue];
}
- (CGFloat)barChart:(SimpleBarChart *)barChart valueForSaMeetRequirementsBarAtIndex:(NSUInteger)index
{
	return [[_saMeetRequirements objectAtIndex:index] floatValue];
}
- (CGFloat)barChart:(SimpleBarChart *)barChart valueForSaLegacyRequirementsBarAtIndex:(NSUInteger)index
{
	return [[_saLegacyRequirements objectAtIndex:index] floatValue];
}
//##########
- (CGFloat)barChart:(SimpleBarChart *)barChart valueForApMonthRequirementsBarAtIndex:(NSUInteger)index
{
	return [[_apMonthRequirements objectAtIndex:index] floatValue];
}
- (CGFloat)barChart:(SimpleBarChart *)barChart valueForApMeetRequirementsBarAtIndex:(NSUInteger)index
{
	return [[_apMeetRequirements objectAtIndex:index] floatValue];
}
- (CGFloat)barChart:(SimpleBarChart *)barChart valueForApLegacyRequirementsBarAtIndex:(NSUInteger)index
{
	return [[_apLegacyRequirements objectAtIndex:index] floatValue];
}
//##########
- (CGFloat)barChart:(SimpleBarChart *)barChart valueForPMonthRequirementsBarAtIndex:(NSUInteger)index
{
	return [[_pMonthRequirements objectAtIndex:index] floatValue];
}
- (CGFloat)barChart:(SimpleBarChart *)barChart valueForPMeetRequirementsBarAtIndex:(NSUInteger)index
{
	return [[_pMeetRequirements objectAtIndex:index] floatValue];
}
- (CGFloat)barChart:(SimpleBarChart *)barChart valueForPLegacyRequirementsBarAtIndex:(NSUInteger)index
{
	return [[_pLegacyRequirements objectAtIndex:index] floatValue];
}
//##########
- (NSString *)barChart:(SimpleBarChart *)barChart textForSaBarAtIndex:(NSUInteger)index
{
    return [[_saLegacyRequirements objectAtIndex:index] stringValue];
}
- (NSString *)barChart:(SimpleBarChart *)barChart textForApBarAtIndex:(NSUInteger)index
{
    return [[_apLegacyRequirements objectAtIndex:index] stringValue];
}
- (NSString *)barChart:(SimpleBarChart *)barChart textForPBarAtIndex:(NSUInteger)index
{
    return [[_pLegacyRequirements objectAtIndex:index] stringValue];
}
//##########

- (NSString *)barChart:(SimpleBarChart *)barChart textForBarAtIndex:(NSUInteger)index
{
    //	return [[_reqSumList objectAtIndex:index] stringValue];
    return [[_apLegacyRequirements objectAtIndex:index] stringValue];
    
}

- (NSString *)barChart:(SimpleBarChart *)barChart xLabelForBarAtIndex:(NSUInteger)index
{
    	return [(Dept *)[_deptList objectAtIndex:index] deptShortName];
//    return [(Dept *)[_tempDeptList objectAtIndex:index] deptFullName];
}

////Outstanding
//- (NSString *)barChart:(SimpleBarChart *)barChart textForOutstandingBarAtIndex:(NSUInteger)index
//{
//    return [[_outstandingSumList objectAtIndex:index] stringValue];
//}

- (void)selectAtItem:(int)index
{
    Dept *dept=[ _deptList objectAtIndex:index];
    RequirementDetail *requrite=[[RequirementDetail alloc] init];
    requrite._currentMonth=_currentMonth;
    requrite.reqId=dept.deptId;
    requrite.byType=0;
    NSDateFormatter *formate = [[NSDateFormatter alloc] init];
    formate.dateFormat = @"MMM YYYY";
    NSString *title=[NSString stringWithFormat:@" %@   %@   requirement Detail Info.",dept.deptShortName,[formate stringFromDate:_currentMonth]];
    [[requrite navigationItem] setTitle:title];
    [self._navigationController pushViewController:requrite animated:YES];
}

@end
